package com.demo.event;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;

import java.util.Optional;

@Configuration
public class EventConfig implements ApplicationEventPublisherAware {

    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    @EventListener({CustomEvent.class})
    public void customEventListener(CustomEvent event) {
        System.out.println("---------处理事件：" + event);
        System.out.println("---------处理事件：Source -> " + event.getSource());
    }
}

@Configuration
class EventConfig2 implements InitializingBean {

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void afterPropertiesSet() throws Exception {
        if (applicationEventPublisher == null) {
            System.out.println("注入失败。");
        }

        Optional.ofNullable(applicationEventPublisher).ifPresent(applicationEventPublisher1 -> {
            System.out.println("---------" + applicationEventPublisher);
        });
    }
}